<template>
  <div class="order-management-container">
    <el-page-header @back="$router.go(-1)">
      <template #content>
        <span class="text-large font-600 mr-3">我的订单</span>
      </template>
    </el-page-header>

    <el-skeleton :rows="6" animated v-if="loading" />
    <el-alert v-if="error" type="error" :title="error.message" show-icon />

    <el-tabs v-model="activeStatus" @tab-change="fetchOrders">
      <el-tab-pane label="待支付" name="unpaid">
        <order-list :orders="filteredOrders('unpaid')" @refresh="fetchOrders" />
      </el-tab-pane>
      <el-tab-pane label="待发货" name="pending">
        <order-list :orders="filteredOrders('pending')" @refresh="fetchOrders" />
      </el-tab-pane>
      <el-tab-pane label="已发货" name="delivered">
        <order-list :orders="filteredOrders('delivered')" @refresh="fetchOrders" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import OrderList from '@/components/OrderList.vue';

const apiBase = ref(import.meta.env.VITE_API_BASE || '');
const activeStatus = ref('unpaid');
const orders = ref([]);
const loading = ref(true);
const error = ref(null);

const statusMap = {
  unpaid: order => order.order_payment_status === 0,
  pending: order => order.order_payment_status === 1 && order.order_delivery_status === 0,
  delivered: order => order.order_delivery_status === 1
};

const filteredOrders = computed(() => (type) => {
  return orders.value.filter(statusMap[type]);
});

const fetchOrders = async () => {
  try {
    loading.value = true;
    const { data } = await axios.get(`${import.meta.env.VITE_API_BASE}/order`);
    orders.value = Array.isArray(data) ? data : [data];
    orders.value.forEach(order => {
      order.product_image = `${apiBase.value}/product_images/${order.product_image.split('\\').pop()}`;
    });
  } catch (err) {
    error.value = err;
    ElMessage.error('订单加载失败');
  } finally {
    loading.value = false;
  }
};

onMounted(fetchOrders);
</script>

<style scoped>
.order-management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}
</style>